const app = getApp();
import api from "../../utils/api.js";

Page({
  data: {
    imgBaseUrl: "",
    query: "",
    sortOptions: ["最新发布", "最早发布", "标题 A→Z", "标题 Z→A"],
    sortIndex: 0,
    stories: [],
    allStories: [],
    pageIndex: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    refreshing: false,
    modal: { show: false, data: { id: "", title: "", content: "", audio: "" } },
    isPlaying: false,
    audioCtx: null,
    audioLoading: false,
  },

  onLoad() {
    this.setData({ imgBaseUrl: api.ENV.imgBaseUrl || "" });
    this.fetchStories(true);
  },

  // 构建后端 MP3 播放地址（接口端点，用于获取真实直链）
  getMp3Url(id) {
    if (!id && id !== 0) return "";
    // 注意：真机调试无法访问 localhost，请改为局域网 IP 或可访问的域名并在小程序后台配置合法域名
    const BASE =
      (app.globalData && app.globalData.apiBase) || "www.hovoy.cn:8082";
    return `${BASE}/api/story/${id}/mp3`;
  },

  // 调用后端接口，获取真实可播放的 MP3 直链
  fetchMp3RealUrl(id) {
    const apiEndpoint = this.getMp3Url(id);
    return new Promise((resolve, reject) => {
      if (!apiEndpoint) {
        reject(new Error("INVALID_ID"));
        return;
      }
      wx.request({
        url: apiEndpoint,
        method: "GET",
        success: (res) => {
          console.log(res);
          const url =
            res &&
            res.data &&
            res.data.code === 200 &&
            Array.isArray(res.data.data) &&
            res.data.data[0]
              ? res.data.data[0]
              : "";
          if (url) resolve(url);
          else reject(new Error("EMPTY_URL"));
        },
        fail: (err) => reject(err),
      });
    });
  },

  // 构建安全的摘要文本，避免在 WXML 中调用函数导致取值异常
  buildExcerpt(content, maxLen = 60) {
    const s = (content ?? "").toString().replace(/\s+/g, " ").trim();
    if (!s) return "";
    return s.length > maxLen ? s.slice(0, maxLen) + "…" : s;
  },

  // 拉取故事列表（支持刷新）
  fetchStories(reset = false) {
    if (this.data.loading) return;
    const apiUrl = api.endpoints.STORY_LIST;
    console.log(apiUrl);
    this.setData({ loading: true });

    wx.request({
      url: apiUrl,
      method: "GET",
      success: (res) => {
        let list = [];
        console.log(res);
        if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
          list = res.data.data;
        } else {
          // 本地兜底数据
          list = [
            {
              id: 1,
              title: "校史回望",
              content: "这是一个关于学校历史的故事……",
              createTime: "2024-01-01",
            },
            {
              id: 2,
              title: "老一辈的坚持",
              content: "那年冬天，先辈们在艰苦条件下……",
              createTime: "2024-03-10",
            },
            {
              id: 3,
              title: "校园的第一棵树",
              content: "操场边的那棵树，见证了……",
              createTime: "2023-11-02",
            },
          ];
        }
        this.setData({ allStories: list });
        console.log(this.data.allStories);
        if (reset) {
          this.setData({ pageIndex: 1, hasMore: true, stories: [] });
        }
        this.applyQueryAndSort(true);
      },
      fail: () => {
        // 网络失败也使用兜底
        const list = [
          {
            id: 1,
            title: "校史回望",
            content: "这是一个关于学校历史的故事……",
            createTime: "2024-01-01",
          },
          {
            id: 2,
            title: "老一辈的坚持",
            content: "那年冬天，先辈们在艰苦条件下……",
            createTime: "2024-03-10",
          },
          {
            id: 3,
            title: "校园的第一棵树",
            content: "操场边的那棵树，见证了……",
            createTime: "2023-11-02",
          },
        ];
        this.setData({ allStories: list });
        this.applyQueryAndSort(true);
      },
      complete: () => {
        this.setData({ loading: false, refreshing: false });
      },
    });
  },

  // 过滤 + 排序 + 分页
  applyQueryAndSort(resetPage = false) {
    let arr = [...this.data.allStories];
    const q = (this.data.query || "").trim().toLowerCase();
    if (q) {
      arr = arr.filter(
        (it) =>
          (it.title || "").toLowerCase().includes(q) ||
          (it.content || "").toLowerCase().includes(q)
      );
    }
    switch (this.data.sortIndex) {
      case 0: // 最新发布
        arr.sort(
          (a, b) => new Date(b.createTime || 0) - new Date(a.createTime || 0)
        );
        break;
      case 1: // 最早发布
        arr.sort(
          (a, b) => new Date(a.createTime || 0) - new Date(b.createTime || 0)
        );
        break;
      case 2:
        arr.sort((a, b) => (a.title || "").localeCompare(b.title || ""));
        break;
      case 3:
        arr.sort((a, b) => (b.title || "").localeCompare(a.title || ""));
        break;
    }

    let pageIndex = this.data.pageIndex;
    if (resetPage) pageIndex = 1;

    const start = (pageIndex - 1) * this.data.pageSize;
    const next = arr.slice(start, start + this.data.pageSize);
    const hasMore = start + this.data.pageSize < arr.length;

    const mapped = next.map((it) => ({
      ...it,
      excerpt: this.buildExcerpt(it && it.content, 60),
    }));

    this.setData({
      stories: pageIndex === 1 ? mapped : this.data.stories.concat(mapped),
      hasMore,
      pageIndex,
    });
  },

  onInput(e) {
    this.setData({ query: e.detail.value || "" });
  },
  onSearch() {
    this.setData({ pageIndex: 1, hasMore: true, stories: [] });
    this.applyQueryAndSort(true);
  },
  onSortChange(e) {
    const idx = Number(e.detail.value) || 0;
    this.setData({ sortIndex: idx, pageIndex: 1, hasMore: true, stories: [] });
    this.applyQueryAndSort(true);
  },

  onRefresh() {
    this.setData({ refreshing: true });
    this.fetchStories(true);
  },

  onReachListBottom() {
    if (!this.data.hasMore || this.data.loading) return;
    this.setData({ pageIndex: this.data.pageIndex + 1 });
    this.applyQueryAndSort(false);
  },

  openStory(e) {
    const idx = e.currentTarget.dataset.index;
    const item = this.data.stories[idx];
    if (!item) return;
    // 打开新故事详情前停止当前音频
    this.stopAudio();
    this.setData({
      modal: { show: true, data: item },
      isPlaying: false,
      audioLoading: false,
    });
  },
  closeModal() {
    this.stopAudio();
    this.setData({
      modal: {
        show: false,
        data: { id: "", title: "", content: "", audio: "" },
      },
      isPlaying: false,
      audioLoading: false,
    });
  },

  toggleTTS() {
    const id = this.data.modal?.data?.id;
    if (!id && id !== 0) {
      wx.showToast({ title: "缺少音频资源", icon: "none" });
      return;
    }
    if (!this.data.audioCtx) {
      const ctx = wx.createInnerAudioContext();
      // 事件绑定
      ctx.onPlay(() => this.setData({ isPlaying: true, audioLoading: false }));
      ctx.onPause(() => this.setData({ isPlaying: false }));
      ctx.onStop(() => this.setData({ isPlaying: false }));
      ctx.onEnded(() => this.setData({ isPlaying: false }));
      ctx.onWaiting(() => this.setData({ audioLoading: true }));
      ctx.onCanplay(() => this.setData({ audioLoading: false }));
      ctx.onError((e) => {
        this.setData({ isPlaying: false, audioLoading: false });
        wx.showToast({ title: "音频播放出错", icon: "none" });
        console.error("audio error", e);
      });
      this.setData({ audioCtx: ctx });
    }
    const ctx = this.data.audioCtx;

    if (this.data.isPlaying) {
      // 正在播放则暂停
      try {
        ctx.pause();
      } catch (e) {}
      this.setData({ isPlaying: false });
      return;
    }

    // 未播放：若已缓存真实直链则直接播放，否则点击时发起请求获取直链并缓存到 item 后再播放
    const cached =
      this.data.modal && this.data.modal.data ? this.data.modal.data.audio : "";
    if (cached) {
      this.setData({ audioLoading: true });
      try {
        ctx.src = cached;
        ctx.play();
      } catch (e) {
        this.setData({ audioLoading: false });
        wx.showToast({ title: "音频启动失败", icon: "none" });
      }
      return;
    }

    // 首次点击：请求真实 mp3 直链
    this.setData({ audioLoading: true });
    this.fetchMp3RealUrl(id)
      .then((realUrl) => {
        this.setData({ "modal.data.audio": realUrl });
        try {
          ctx.src = realUrl;
          ctx.play();
        } catch (e) {
          this.setData({ audioLoading: false });
          wx.showToast({ title: "音频启动失败", icon: "none" });
        }
      })
      .catch((err) => {
        this.setData({ audioLoading: false });
        wx.showToast({ title: "获取音频链接失败", icon: "none" });
        console.error("fetchMp3RealUrl error", err);
      });
  },

  stopAudio() {
    if (this.data.audioCtx) {
      try {
        this.data.audioCtx.stop();
      } catch (e) {}
    }
    this.setData({ isPlaying: false, audioLoading: false });
  },

  onHide() {
    // 页面隐藏时也停止音频，避免后台持续播放
    this.stopAudio();
  },

  onUnload() {
    this.stopAudio();
    // 彻底释放资源
    if (this.data.audioCtx) {
      try {
        this.data.audioCtx.destroy();
      } catch (e) {}
      this.setData({ audioCtx: null });
    }
  },
});
